<template>
  <div class="app-container">
    <div class="top">
      <span>
        <span @click="back()"><svg-icon icon-class="fanhui" /></span>
      </span>
      <span class="top-right">
        <el-button class="btn" type="primary" size="mini" @click="save">保存</el-button>
<!--        <el-button class="btn" type="success" size="mini">保存预览</el-button>-->
      </span>

    </div>

    <div class="landPage_info">

      <el-row class="landPage-container" type="flex" justify="space-between">
        <el-col :span="6">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>基础组件</span>
            </div>

            <draggable  :group="{ name: 'components', pull: 'clone', put: false, animation: 200 }" :clone="cloneComponent" :sort="false" chosen-class="chosen" force-fallback="true" animation="1000" :list="componentsInfos" class="component-thumbnail dragArea list-group" @end="fromDragEnd" >
              <div class="component-thumbnail-item list-group-item" v-for="(item, index) in componentsInfos" :key="index" >
                <template v-if="item.image">
                  <div class="image-wrapper draggable-item">
                    <img :src="item.image"/>
                  </div>
                  <div class="component-thumbnail-text">
                    <span>{{ item.title }}</span>
                  </div>
                </template>
              </div>
            </draggable>
          </el-card>
        </el-col>
        <el-col :span="9">
          <div class="landPage-content-container">
            <div class="landPage-content-wrapper">
              <div class="landPage-content-head" @click="onHeaderClick">
                <div class="head-title ellipsis">{{ landPageData.title }}</div>
              </div>
              <div class="landPage-content">
                <draggable
                  group="components"
                  :list="chosenComponents"
                  @choose="choose"
                  class="landPage-content-draggable"
                  animation="300"
                  ghost-class="ghost"
                  @add="addComponent"
                >
                  <div class="list-group-item dragArea list-group" v-for="(component, index) in chosenComponents" @click="onComponentClicked(component)" :key="component.id">
                    <!-- 动态组件加载 -->
                    <component
                      v-bind:is="component.registerName" :componentData="component.componentData"  :componentId="component.id" :class="`${ selectedComponentId === component.id?'activeComponent':''}`"></component>
                  </div>
                </draggable>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>{{ selectedComponent ? selectedComponent.title : '落地页信息' }}</span>
            </div>
            <div class="text item">
              <template v-if="selectedComponentId">
                <component
                  v-bind:is="`${selectedComponent.registerName}-setting`" v-bind.sync="selectedComponent"></component>
              </template>
              <el-form  v-show="!selectedComponentId" ref="basicInfoForm" :model="landPageData" :rules="landPageRules" label-width="120px">
                <el-form-item label="名称" prop="name">
                  <el-input v-model="landPageData.name"></el-input>
                </el-form-item>
                <el-form-item label="标题" prop="title">
                  <el-input v-model="landPageData.title"></el-input>
                </el-form-item>
              </el-form>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <el-backtop ref="top" :bottom="100">T</el-backtop>
  </div>
</template>
<script>
import api from '@/api/landPage'

// 动态加载目录下的数据
const path = require('path')
const files = require.context('./components', false, /\.vue$/)
const componentsInfos = []
const modules = {}
files.keys().forEach(key => {
  const component = files(key).default || files(key)
  console.log(component)
  const componentData = component.defaultComponentData ? JSON.parse(JSON.stringify(component.defaultComponentData)) : {}
  componentsInfos.push({ title: component.title, image: component.image, registerName: component.registerName, componentData })
  const name = path.basename(key, '.vue')
  modules[name] = files(key).default || files(key)
})

export default {
  name: '',
  props: {},
  components: { ...modules },
  data() {
    return {
      id: '',
      draggableItem: 'draggable-item',
      componentsInfos: componentsInfos,
      chosenComponents: [],
      selectedComponent: null,
      dragComponent: null,
      selectedComponentId: null,
      landPageData: {
        title: '',
        name: '',
        status: ''
      },
      landPageRules: {
        name: [
          { required: true, message: '名称不能为空' }
        ],
        title: [
          { required: true, message: '标题不能为空' }
        ]
      }
    }
  },
  mounted() {
  },
  created() {
    const id = this.$router.currentRoute.query.id
    if (id) {
      this.landPageData.id = id
      api.data(id).then(res => {
        const data = res.data
        this.landPageData.title = data.title
        this.landPageData.name = data.name
        this.landPageData.status = data.status
        const content = data.content
        if (content) {
          this.chosenComponents = JSON.parse(data.content)
        }
      })
    }
    const _this = this
    document.onkeydown = function(e) {
      const key = window.event.keyCode
      // 删除键
      if (key === 46) {
        _this.deleteComponent()
      }
    }
  },
  methods: {
    back() {
      this.$router.go(-1)
    },
    cloneComponent(component) {
      const result = JSON.parse(JSON.stringify(component))
      result.id = new Date().getTime()
      this.dragComponent = result
      return result
    },
    addComponent() {
      this.selectedComponent = this.dragComponent
      this.selectedComponentId = this.dragComponent.id
      this.dragComponent = null
    },
    choose(component) {

    },
    onComponentClicked(component) {
      this.selectedComponentId = component.id
      this.selectedComponent = component
    },
    fromDragEnd(component) {
    },
    onHeaderClick() {
      this.selectedComponentId = null
    },
    deleteComponent() {
      if (this.selectedComponentId) {
        let index = -1
        for (let i = 0; i < this.chosenComponents.length; i++) {
          if (this.selectedComponentId === this.chosenComponents[i].id) {
            index = i
            break
          }
        }
        if (index > -1) {
          this.chosenComponents.splice(index, 1)
          this.selectedComponentId = null
          this.selectedComponent = null
        }
      }
    },
    save() {
      this.$refs['basicInfoForm'].validate((valid) => {
        if (valid) {
          for (let i = 0; i < this.chosenComponents.length; i++) {
            const component = this.chosenComponents[i]
            component.image = null
          }
          const data = {
            id: this.landPageData.id,
            name: this.landPageData.name,
            title: this.landPageData.title,
            status: this.landPageData.status,
            content: JSON.stringify(this.chosenComponents)
          }
          api.saveOrUpdate(data).then(res => {
            this.back()
          })
        } else {
          if (this.selectedComponentId != null) {
            this.selectedComponent = null
            this.selectedComponentId = null
          }
        }
      })
    }
  }
}
</script>
<style scoped>

.top-right {
  float: right;
}

.landPage-container {
  margin-top: 30px;
}

.component-thumbnail {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  flex-direction: row;
  cursor: move;
}

.component-thumbnail-item {
  text-align: center;
  border-color: #FFFFFF;
  border-style: solid ;
  border-width: 1px;
}
.component-thumbnail-item .image-wrapper {
  width: 130px;
  height: 130px;
}
.component-thumbnail-item img {
  width: 100%;
}
.component-thumbnail-text {
  text-align: center;
  padding: 8px;
}

.landPage-content {
  /*height: 100%;*/
}

.landPage-content-container {
  width: 100%;
  margin:0 auto;
  padding-top:20px;
  padding-bottom: 20px;
  display: flex;
  justify-content: space-between;
  background-color: #606266;
}

.landPage-content-wrapper {
  min-width: 375px;
  background-color: #fff;
  margin: 0 auto;
  min-height: 667px;
  max-height: 667px;
  max-width: 375px;
}

.landPage-content-head {
  background: url('../../../static/images/phone.png') no-repeat center center;
  background-size: 100% 100%;
  height: 85px;
}

.landPage-content-head  .head-title{
  padding-top: 48px;
  text-align: center;
}

.chosen {
  border-color: #1890ff;
  border-style: dashed ;
  border-width: 1px;
}

.ghost {
  border-color: #1367ce;
  border-style: solid ;
  border-width: 2px;
  background-color: #f6f6f8;
  text-align: center;
  height: 100px;
}

.ghost div {
  visibility: hidden;
}

.activeComponent {
  border-color: #1367ce;
  border-style: solid ;
  border-width: 1px;
}

.landPage-content-draggable {
  height: 582px;
  overflow-y: auto;
  overflow-x: hidden;
}

.landPage-content-draggable::-webkit-scrollbar {
  width: 6px;
  background-color: #F5F5F5;
}

.landPage-content-draggable::-webkit-scrollbar-thumb {
  background-color: #9b9999;
  -webkit-border-radius: 6px;
}
.landPage-content-draggable::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
  background-color: #F5F5F5;
}
</style>
